<template>
  <a-row class="mt-1 mb-2 pb-2 border-bottom">
    <a-col :span="12" style="line-height: 32px">
      <a-typography-text class="mr-3">{{ fileCreateTime }}</a-typography-text>
      <a-typography-text v-if="fileSize">{{ fileSize }}</a-typography-text>
    </a-col>
    <a-col :span="12" class="text-right">
      <a-button class="mr-2" size="small" type="text" @click="getArticleInfo">
        <ReloadOutlined />
      </a-button>
      <a-button type="primary" @click="edit">
        <template #icon>
          <EditOutlined />
        </template>
        编辑内容
      </a-button>
    </a-col>
  </a-row>
  <div ref="mdViewTitle" id="md-view-title">
    <a-typography-title
      :level="5"
      v-for="item in titleCon"
      :key="item.key"
      :title="item.key"
      :class="[`ml-${item.indent * 2}`]"
      :style="{ 'font-size': `${20 - item.indent}px` }"
      @click="handleTitleClick(item.ele)"
    >
      {{ item.key }}
    </a-typography-title>
  </div>
  <a-divider
    v-if="titleCon.length > 0"
    dashed
    style="border-color: rgb(88 146 248)"
    class="mt-2"
  />
  <section ref="mdView" id="md-view" v-html="content"></section>
  <a-empty v-if="!content" class="mt-8" />
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { getArticle } from '@/services'
import { debounce } from '@/utils/throttleDebounce'
import { ArticleModel } from '@/services/service'
import { message } from 'ant-design-vue'
import { EditOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import marked from 'marked'
import moment from 'moment'

interface ITitleCon {
  key: string
  indent: number
  ele: HTMLElement
}

export default defineComponent({
  name: 'file-content',
  components: {
    EditOutlined,
    ReloadOutlined
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const currentFile = computed(() => store.state.db.currentFile)
    const content = ref('')
    const titleCon = ref<ITitleCon[]>([])
    const mdViewTitle = ref()
    const mdView = ref()
    const article = ref({} as ArticleModel)

    const fileSize = computed(() => {
      let len = article.value.content?.length || 0
      if (len < 10) {
        return ''
      }
      return len > 1048576
        ? (len / 1048576).toFixed(2) + 'M'
        : (len / 1024).toFixed(2) + 'KB'
    })

    const fileCreateTime = computed(() => {
      return article.value.create_time
        ? moment(article.value.create_time).format('YYYY年MM月DD日')
        : ''
    })

    const getArticleInfo = debounce(async function () {
      let load = message.loading('读取文件中...')
      let res = await getArticle(currentFile.value.article_id)

      if (res.code) {
        article.value = res.data

        content.value = marked(article.value.content || '')

        initTitle()
      }

      load()
    })

    function initTitle() {
      nextTick(() => {
        let hs = mdView.value.querySelectorAll('h1,h2,h3,h4,h5,h6')
        let tags = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']

        titleCon.value = []
        Array.from(hs).forEach((e) => {
          let index = tags.indexOf((e as HTMLElement).tagName)
          titleCon.value.push({
            key: (e as HTMLElement).innerText,
            indent: index > -1 ? index : 0,
            ele: e as HTMLElement
          })
        })
      })
    }

    function handleTitleClick(e: HTMLElement) {
      e?.scrollIntoView({ behavior: 'smooth' })
    }

    const edit = function () {
      router.push({
        path: '/edit'
      })
    }

    watch(
      () => currentFile.value,
      () => {
        getArticleInfo()
      }
    )

    return {
      currentFile,
      mdViewTitle,
      mdView,
      content,
      titleCon,
      getArticleInfo,
      fileSize,
      fileCreateTime,
      edit,
      handleTitleClick
    }
  }
})
</script>

<style lang="less">
@import url('./mdview.less');
</style>
